package com.xy.tool.webmvc.interceptor;

import com.xy.lang.domain.Result;
import com.xy.tool.context.UserContext;
import com.xy.tool.context.UserContextHolder;
import com.xy.tool.json.JsonUtils;
import com.xy.tool.jwt.TokenParser;
import com.xy.tool.util.LogUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.lang.Nullable;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.Objects;

import static com.xy.tool.context.UserContext.REQUEST_HEADER_AUTHORIZATION;

@Slf4j
public class TokenInterceptor extends HandlerInterceptorAdapter {

    private final TokenParser tokenParser;

    public TokenInterceptor(TokenParser tokenParser) {
        Objects.requireNonNull(tokenParser);
        this.tokenParser = tokenParser;
    }

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        if("OPTIONS".equals(request.getMethod())) {
            return true;
        }
        String token = request.getHeader(REQUEST_HEADER_AUTHORIZATION);
        if(!StringUtils.hasText(token)) {
            response.sendError(HttpStatus.UNAUTHORIZED.value(), "未找到" + REQUEST_HEADER_AUTHORIZATION + "信息");
            return false;
        }
        Result<UserContext> result = tokenParser.verify(token);
        if(!result.wasSuccess()) {
            LogUtils.warn(log, JsonUtils.toJson(result));
            return false;
        }
        UserContextHolder.set(result.getData());
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response,
                                Object handler,
                                @Nullable Exception ex) throws Exception {
        UserContextHolder.remove();
    }

}
